import * as THREE from 'three';
import M from 'scripts/main.js';
import { TWEEN } from 'three/addons/libs/tween.module.min.js';
import { CSS3DRenderer, CSS3DObject } from 'three/addons/renderers/CSS3DRenderer.js';
import {Shop} from 'scripts/shop.js';

class BuyBook {
	constructor(param){	
		let animationID;
		let detail = '学完本课，你一共掌握$1个汉字，占常用汉字的$2%。本课中还将学到$3个词语和$4个句式，预计学习时间3小时。最多可获得金币500个。<br>此课本的加成点数为<br>朗读加成：⭐<br>考核加成：⭐⭐<br>教学加成：⭐';

		let camera, scene, renderer;
		let controls;
		let objects = [],targets = [];
		const m = new M();

		init();

		async function init() {
			THREE.Cache.enabled = true;
			const loca = m.parseString4(param.id,4);
			const data = await m.callAPI({webapi:"getBook",location:loca,lan:1,bid:1});
			detail = detail.replace("$1",(param.id+1)*16).replace("$2",data.percent).replace("$3",data.ci).replace("$4",data.ju);
			camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1000, 10000 );
			camera.position.z = 6000;

			scene = new THREE.Scene();

			const card = document.createElement( 'div' );
			card.className = 'card';
			card.style.backgroundColor = 'rgba(0,127,127,' + m.getTransparency(param.rare) + ')';
			for ( let i = 0; i < data.zis.length; i ++ ) {
				const div = document.createElement( 'div' );
				div.className = 'zi';
				div.style.backgroundColor = 'rgba(0,127,127,' +  m.getTransparency(param.rare) + ')';
				div.style.top = (Math.floor(i/4)*120+5)+"px";
				div.style.left = ((i%4)*120+5)+"px";
				div.textContent = data.zis[i].zi;
				card.appendChild( div );
			}

			const number = document.createElement( 'div' );
			number.className = 'number';
			number.textContent = m.getBookNo(param.id);
			card.appendChild( number );

			const price = document.createElement( 'div' );
			price.className = 'price';
			price.textContent = '💰'+m.getPrice(param.rare);
			card.appendChild( price );

			const rare = document.createElement( 'div' );
			rare.className = 'rare';
			rare.innerHTML = m.getRare(param.rare);
			card.appendChild( rare );

			const objectCSS = new CSS3DObject( card );
			objectCSS.position.x = 0;
			objectCSS.position.y = 0;
			objectCSS.position.z = 6000;
			scene.add( objectCSS );

			objects.push( objectCSS );

			const object = new THREE.Object3D();

			object.position.x = -260;
			object.position.y = 0;
			object.position.z = 5000;

			targets.push( object );

			const info = document.createElement( 'div' );
			info.className = 'card';
			info.style.backgroundColor = 'rgba(0,127,127,' + m.getTransparency(param.rare) + ')';
			
			const details = document.createElement( 'div' );
			details.className = 'detail';
			details.innerHTML = detail;
			info.appendChild( details );

			const buy = document.createElement( 'div' );
			buy.className = 'buy';
			buy.textContent = '购买';
			info.appendChild( buy );
			buy.addEventListener('pointerdown', function() { 
				let money = parseFloat(m.loadItem("money"));
				let price = m.getPrice(param.rare);
				if (price >money){
					alert("您的可用金币不足，请从钱包中提现，或去市场购买。");
				}else{
					if (confirm("确定支付"+price+"个金币购买此课本吗？")){
						//TOFO:增加荣誉值
						data.id=param.id;
						data.rare=param.rare;
						data.time = new Date().getTime();
						let books = m.loadJson("books");
						if (!books) books=[];
						money -= price;
						data.index = books.length;
						books.push(data);
						m.saveJson("books",books);
						m.setMoney(money);
						alert("购买成功，课本已放入您的收藏中。");
						goshop();
					}
				}
			});


			const objectCSS1 = new CSS3DObject( info );
			objectCSS1.position.x = 0;
			objectCSS1.position.y = 0;
			objectCSS1.position.z = 6000;
			scene.add( objectCSS1 );

			objects.push( objectCSS1 );

			const object1 = new THREE.Object3D();

			object1.position.x = 260;
			object1.position.y = 0;
			object1.position.z = 5000;

			targets.push( object1 );
			
			renderer = new CSS3DRenderer();
			renderer.setSize( window.innerWidth, window.innerHeight );
			document.getElementById( 'container' ).appendChild( renderer.domElement );

			transform( targets, 1000 );

			m.display("goback",true);
			m.getNode("goback").addEventListener('pointerdown', goshop);

			window.addEventListener( 'resize', onWindowResize );
			animate();
		}
		function goshop(){
			destroy();
			new Shop();
		}
		function transform( targets, duration ) {

			TWEEN.removeAll();

			for ( let i = 0; i < objects.length; i ++ ) {

				const object = objects[ i ];
				const target = targets[ i ];

				new TWEEN.Tween( object.position )
					.to( { x: target.position.x, y: target.position.y, z: target.position.z }, 2 * duration )
					.easing( TWEEN.Easing.Exponential.InOut )
					.start();

			}

			new TWEEN.Tween( this )
				.to( {}, duration * 2 )
				.onUpdate( render )
				.start();

		}

		function onWindowResize() {

			camera.aspect = window.innerWidth / window.innerHeight;
			camera.updateProjectionMatrix();

			renderer.setSize( window.innerWidth, window.innerHeight );

			render();

		}

		function animate() {

			animationID = requestAnimationFrame( animate );

			TWEEN.update();


		}

		function render() {

			renderer.render( scene, camera );

		}

		function destroy(){
			cancelAnimationFrame(animationID)
			TWEEN.removeAll();
			scene.clear();
			renderer.content = null;

			m.getNode("goback").removeEventListener('pointerdown', goshop);
			window.removeEventListener( 'resize', onWindowResize );
			let c = m.getNode("container");
			m.getNode("container").removeChild(renderer.domElement);
			scene = null;
			camera = null;
			renderer = null;
			objects = null;
			targets = null;
		}			
	}
}
export { BuyBook };